package com.danikula.videocache.util;

import ohos.app.Context;
import ohos.app.Environment;

import ohos.data.usage.DataUsage;
import ohos.data.usage.MountState;

import java.io.File;
import java.util.Optional;

import static ohos.data.usage.MountState.DISK_MOUNTED;

/**
 * Provides application storage paths
 *
 * @author Sergey Tarasevich (nostra13[at]gmail[dot]com)
 * @since 1.0.0
 */
public final class StorageUtils {
    private static final String TAG = "StorageUtils";
    private static final String INDIVIDUAL_DIR_NAME = "video-cache";

    /**
     * Returns individual application cache directory (for only video caching from Proxy). Cache directory will be
     * created on SD card <i>("/Android/data/[app_package_name]/cache/video-cache")</i> if card is mounted .
     * Else - Android defines cache directory on device's file system.
     *
     * @param context Application context
     * @return Cache {@link File directory}
     */
    public static File getIndividualCacheDirectory(Context context) {
        File cacheDir = getCacheDirectory(context, true);
        return new File(cacheDir, INDIVIDUAL_DIR_NAME);
    }

    /**
     * Returns application cache directory. Cache directory will be created on SD card
     * <i>("/Android/data/[app_package_name]/cache")</i> (if card is mounted and app has appropriate permission) or
     * on device's file system depending incoming parameters.
     *
     * @param context        Application context
     * @param preferExternal Whether prefer external location for cache
     * @return Cache {@link File directory}.<br />
     * <b>NOTE:</b> Can be null in some unpredictable cases (if SD card is unmounted and
     * {@link Context#getCacheDir() Context.getCacheDir()} returns null).
     */
    private static File getCacheDirectory(Context context, boolean preferExternal) {
        Optional<File> appCacheDir = Optional.empty();
        File cacheDir;
        MountState externalStorageState = DataUsage.getDiskMountedStatus();
        if (preferExternal && DISK_MOUNTED.equals(externalStorageState)) {
            appCacheDir = getExternalCacheDir(context);
        }
        if (appCacheDir == null || !appCacheDir.isPresent() || appCacheDir.get() == null) {
            cacheDir = context.getExternalCacheDir();
        } else {
            cacheDir = appCacheDir.get();
        }
        if (cacheDir == null) {
            String cacheDirPath = "/data/data/" + context.getBundleName() + "/cache/";
            LogUtil.warn(TAG, "Can't define system cache directory! '" + cacheDirPath + "%s' will be used.");
            cacheDir = new File(cacheDirPath);
        }

        return cacheDir;
    }

    private static Optional<File> getExternalCacheDir(Context context) {
        File dataDir = new File(new File(Environment.DIRECTORY_MOVIES, "Harmony"), "data");
        File appCacheDir = new File(new File(dataDir, context.getBundleName()), "cache");
        if (!appCacheDir.exists()) {
            if (!appCacheDir.mkdirs()) {
                LogUtil.warn(TAG, "Unable to create external cache directory");
                return Optional.empty();
            }
        }
        return Optional.of(appCacheDir);
    }
}
